﻿using System.Collections.Generic;
using FrameWork.UICore;
using FrameWork.Util.Expansion;
using UnityEngine;
using UnityEngine.Rendering;
using Transform = UnityEngine.Transform;

namespace FrameWork.Managers
{
    public partial class UIManager
    {
        private class UIContainer
        {
            /// <summary>
            /// 同层UI之间的Sort间隔
            /// </summary>
            public const int LayerStep = 50;
            
            public int CurTopLayer { get; private set; } = 0;
            
            public EUILayer UILayer { get; private set; }
            
            private readonly Stack<UIBase> _uiStack = new Stack<UIBase>();
            
            private readonly Queue<UIBase> _optionTempQueue = new Queue<UIBase>();

            private Transform LayerRoot { get; set; }

            public UIContainer(EUILayer uiLayer)
            {
                this.UILayer = uiLayer;
                LayerRoot = UIManager.GetInstance().GetUILayerRoot(uiLayer);
            }

            public void OnOpenUI(UIBase ui)
            {
                //设置UI父物体和层级
                ui.transform.SetParentAndResetLocal(LayerRoot);
                var sortingGroup = ui.gameObject.GetOrAddComponent<SortingGroup>();
                CurTopLayer += LayerStep;
                sortingGroup.sortingOrder = CurTopLayer;
                ui.gameObject.SetActive(true);
                
                var rectTransform = ui.GetComponent<RectTransform>();
                rectTransform.anchorMin = new Vector2(0, 0);  
                rectTransform.anchorMax = new Vector2(1, 1);  
                rectTransform.offsetMin = Vector2.zero; 
                rectTransform.offsetMax = Vector2.zero;
                rectTransform.pivot = new Vector2(0.5f, 0.5f);
                
                this._uiStack.Push(ui);
            }

            public bool HasUI<T>() where T : UIBase
            {
                if (_uiStack.Count == 0)
                {
                    return false;
                }

                foreach (UIBase ui in _uiStack)
                {
                    if (ui is T)
                    {
                        return true;
                    }
                }
                
                return false;
            }
        }
    }
}